package com.yiwenup.leetcode.hot;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @PROJECT struct-algorithm
 * @PACKAGE com.yiwenup.leetcode.hot
 * @Author yiwenup
 * @Date 2022-03-14 21:55:34
 * <p>
 * @DESCRIPTION https://leetcode-cn.com/problems/daily-temperatures/
 */
public class No0739 {

    /**
     * 执行用时：22 ms, 在所有 Java 提交中击败了90.82%的用户
     * 内存消耗：57 MB, 在所有 Java 提交中击败了6.19%的用户
     */
    public int[] dailyTemperatures(int[] temperatures) {
        int length = temperatures.length;
        int[] ans = new int[length];
        Deque<Integer> stack = new LinkedList<>();

        for (int i = 0; i < length; i++) {
            int temperature = temperatures[i];
            while (!stack.isEmpty() && temperature > temperatures[stack.peek()]) {
                int idx = stack.pop();
                ans[idx] = i - idx;
            }
            stack.push(i);
        }

        return ans;
    }

    /**
     * 执行用时：1703 ms, 在所有 Java 提交中击败了5.06%的用户
     * 内存消耗：51.1 MB, 在所有 Java 提交中击败了59.22%的用户
     */
    public int[] dailyTemperatures1(int[] temperatures) {
        int[] answers = new int[temperatures.length];

        for (int i = 0; i < answers.length; i++) {
            int counter = 0;
            int temp = temperatures[i];
            boolean flag = true;
            for (int j = i + 1; j < temperatures.length; j++) {
                counter++;
                if (temperatures[j] > temp) {
                    break;
                }
                if (j == temperatures.length - 1) flag = false;
            }
            answers[i] = flag ? counter : 0;
        }

        return answers;
    }
}
